package com.dj.util;

import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

/**
 * 请求工具类
 * @author Jon
 *
 */
public class RequestUtil {
	/**
	 * 编写Get请求的方法。但没有参数传递的时候，可以使用Get请求
	 * 
	 * @param url
	 *            需要请求的URL
	 * @return JSON格式数据
	 */
	public static JSONObject doGetRequest(String url) throws Exception {
		HttpClient client = HttpClientBuilder.create().build();//获取HttpClient请求
		HttpGet httpGet = new HttpGet(url);// HttpGet将使用Get方式发送请求URL
		JSONObject jsonObject = null;
		HttpResponse response = client.execute(httpGet);// 使用HttpResponse接收client执行httpGet的结果
		HttpEntity entity = response.getEntity();// 从response中获取结果，类型为HttpEntity
		if (entity != null) {
			String result = EntityUtils.toString(entity, "UTF-8");// HttpEntity转为字符串类型
			jsonObject = JSONObject.parseObject(result);// 字符串类型转为JSON类型
		}
		return jsonObject;
	}

	/**
	 * 编写Post请求的方法。当我们需要参数传递的时候，可以使用Post请求
	 * 
	 * @param url
	 *            需要请求的URL
	 * @param outStr
	 *            需要传递的参数
	 * @return JSON格式数据
	 */
	public static JSONObject doPostRequest(String url, String outStr) throws Exception {
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httpost = new HttpPost(url);
		JSONObject jsonObject = null;
		httpost.setEntity(new StringEntity(outStr, "UTF-8"));
		HttpResponse response = client.execute(httpost);
		String result = EntityUtils.toString(response.getEntity(), "UTF-8");
		jsonObject = JSONObject.parseObject(result);
		return jsonObject;
	}
	
	/**
	 * 请求第三方接口
	 * @param url
	 * @return
	 */
	public static String doPostRequest(String url, Map<String, String>  params){
		String result = null;
		try{
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			for(Map.Entry<String, String> k:params.entrySet()){
				requestEntity.add(k.getKey(),k.getValue());
			}
			result =new RestTemplate().postForObject(url, requestEntity,String.class);	
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
